package com.weiaibenpao.demo.chislim.ui.fragment;


import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.base.BaseFragment;
import com.weiaibenpao.demo.chislim.bean.DistrictBean;
import com.weiaibenpao.demo.chislim.bean.UserSportsInfoBean;
import com.weiaibenpao.demo.chislim.db.preferences.UserPreferences;
import com.weiaibenpao.demo.chislim.presenter.NormalRunFPresenter;
import com.weiaibenpao.demo.chislim.ui.activity.running.ChinaRunRankActivity;
import com.weiaibenpao.demo.chislim.ui.activity.running.ChinaRunRecordActivity;
import com.weiaibenpao.demo.chislim.ui.activity.running.RegionActivity;
import com.weiaibenpao.demo.chislim.ui.activity.running.StartRunActivity;
import com.weiaibenpao.demo.chislim.ui.widget.DashBoardView;
import com.weiaibenpao.demo.chislim.utils.Utils;
import com.weiaibenpao.demo.chislim.view.NormalRunFView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class ChinaRunFragment extends BaseFragment<NormalRunFView, NormalRunFPresenter> implements NormalRunFView {


    @BindView(R.id.text_region)
    TextView textRegion;
    @BindView(R.id.dashboard_view)
    DashBoardView dashboardView;
    @BindView(R.id.text_run_rank)
    TextView textRunRank;
    @BindView(R.id.tv_run_distance)
    TextView tvRunDistance;
    private String code = "330100";
    private String provinceName = "浙江省杭州市";
    private double districtDistance = 1228.30;
    private double runDistance = 0;
    private int userId;
    private boolean isFirst = true;

    public ChinaRunFragment() {
        // Required empty public constructor
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_china_run;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        userId = UserPreferences.getInstance().getInt(UserPreferences.USER_ID);
        Typeface typeFace = Typeface.createFromAsset(getContext().getAssets(), "fonts/Reducto Condensed SSi Condensed.ttf");
        tvRunDistance.setTypeface(typeFace);
        EventBus.getDefault().register(this);

    }

    @Override
    public void onResume() {
        super.onResume();
       if (isFirst){
           isFirst=false;
           mPresenter.getUserSportsInfo(userId, 23, "");

       }else {
           mPresenter.getUserSportsInfo(userId, 23, code);

       }

    }

    @Override
    protected NormalRunFPresenter initPresenter() {
        return new NormalRunFPresenter();
    }

    @OnClick({R.id.layout_region_more, R.id.btn_start_run, R.id.text_run_rank, R.id.tv_run_distance})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_region_more:
                RegionActivity.openActivity(getContext(), code, provinceName, runDistance, districtDistance);
                break;
            case R.id.btn_start_run:
                if (runDistance >= districtDistance) {
                    showIsGoRun();
                } else {
                    StartRunActivity.openActivity(getContext(), 3, code, (float) runDistance, provinceName, (float) districtDistance, null, 0, 0);
                }
                break;
            case R.id.text_run_rank:
                ChinaRunRankActivity.openActivity(getContext(), code, provinceName);
                break;
            case R.id.tv_run_distance:
                ChinaRunRecordActivity.startNewActivity(getContext());

                break;
        }
    }

    /**
     * 如果跑完，提示是否继续跑
     */
    private void showIsGoRun() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());

        builder.setMessage("该行政区域已跑完，是否再跑一次");
        builder.setNegativeButton("继续跑", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                StartRunActivity.openActivity(getContext(), 3, code, 0, provinceName, (float) districtDistance, null, 0, 0);
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.setCancelable(true);
        AlertDialog dialog = builder.create();
        dialog.show();
        dialog.getButton(dialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.themeColor));
        dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(Color.parseColor("#666666"));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DistrictBean districtBean) {
        initView(districtBean);
    }

    private void initView(DistrictBean districtBean) {
        textRunRank.setText(districtBean.getGradeName());
        textRegion.setText(!TextUtils.isEmpty(districtBean.getLocation()) ? districtBean.getLocation() : provinceName);
        tvRunDistance.setText(Utils.decimalFormat(districtBean.getCurrValue()));
        dashboardView.setMaxValue(districtBean.getDistance());
        dashboardView.setCreditValueWithAnim(districtBean.getCurrValue());
        code = !TextUtils.isEmpty(districtBean.getCode()) ? districtBean.getCode() : code;
        districtDistance = (float) districtBean.getDistance();
        runDistance = (float) districtBean.getCurrValue();
        provinceName = !TextUtils.isEmpty(districtBean.getLocation())?districtBean.getLocation():provinceName;

    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void requestSuccess(UserSportsInfoBean userSportsInfoBean) {
        UserSportsInfoBean.DjqSumSportsResultBean result = userSportsInfoBean.getDjqSumSportsResult();
        UserSportsInfoBean.RankNumberBean rankNumber = userSportsInfoBean.getRankNumber();

        if (result.getId() == null || result.getId() == 0) {
            return;
        }
        if (rankNumber == null) {
            textRunRank.setText("暂无排名");
        } else {
            textRunRank.setText(userSportsInfoBean.getRankNumber().getRownum() == 0 ? "暂无排名" : "第" + userSportsInfoBean.getRankNumber().getRownum() + "名");
        }
        code = result.getCode();
        provinceName = result.getAreaAddress();
        districtDistance = result.getYudingDistance();
        runDistance = result.getFinishDistance();
        textRegion.setText(provinceName);
        tvRunDistance.setText(Utils.decimalFormat(runDistance));
        dashboardView.setMaxValue(districtDistance);
        dashboardView.setCreditValueWithAnim(runDistance);

    }
}
